#!/usr/bin/perl

use strict 'vars';
package main;

use Getopt::Std;
use Cwd;

use vars qw($opt_d $opt_u);

#get command line options
getopts('d:u:');
if ($opt_d eq "") {
    die "Usage: ps-i3-server.pl -d <conf_dir> -u <username>\n";
}
if ($opt_u eq "") {
    $opt_u = "ucb6";
}

chdir ($opt_d) || die "Cannot change to conf directory\n";
opendir (CONF_DIR, ".") || die "Cannot open conf directory\n";

my $filename, my @arr, my $cmd, my $count;
while ($filename = readdir(CONF_DIR)) {
    if ($filename =~ "cfg") {
	@arr = split(/_/, $filename);
	print "Checking i3 on host $arr[1] at port $arr[2]: ";

	open PS, "ssh $opt_u\@$arr[1] \"ps ax|grep i3_server|grep $arr[2]|grep -v grep\"|";

	$count = 0;
	while (<PS>) {
	    $count++;
	}
	if ($count == 0) {
	    print "NO";
	} elsif ($count == 2) {
	    print "YES";
	} elsif ($count == 1) {
	    print "PARTIAL";
	} else {
	    print "ERROR$count";
	}
	print "\n";
    }
}

close CONF_DIR;
